﻿using System;
using Microsoft.SharePoint;
using SPContrib.Artifacts.Collections;

namespace SPContrib.Artifacts.Definitions
{
    public class FeatureActionDefinition
    {
        private Action _action;
        private SPFeature _feature;

        public EventHandler<EventArgs<Exception>> OnError = delegate { };

        private FeatureActionDefinition(SPFeature feature)
        {
            this._feature = feature;
        }

        internal FeatureActionDefinition(string action, SPFeature feature)
            :this(feature)
        {
            // TODO: improve actions, so the user can define what to call the actions via a setting in the farm
            
            // TODO: add these also
            // update-modules

            // update-columns

            // update-lists

            // TODO: add logging
            switch (action.ToLowerInvariant())
            {
                case "synchronize-ctypes":
                    // TODO: add options on what to sync
                    this._action = SynchronizeContentTypes;
                    break;
                case "synchronize-modules":
                    // TODO: add options on what to sync
                    this._action = SynchronizeModules;
                    break;
                default:
                    this._action = delegate { }; // do nothing
                    break;
            }
        }

        public void Execute()
        {
            try
            {
                _action();
            }
            catch (Exception e)
            {
                OnError(this, new EventArgs<Exception>(e));
            }
        }

        private void SynchronizeContentTypes() 
        {
            ContentTypeDefinitionCollection ctypes = new ContentTypeDefinitionCollection(this._feature);
            ctypes.Synchronize();
        }

        private void SynchronizeModules()
        {
            ModuleDefinitionCollection modules = new ModuleDefinitionCollection(this._feature);
            modules.Synchronize();
        }
    }
}
